package com.hyving.home.okhttpdemo.cron;

import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ClientRunner implements ApplicationRunner {

    @Autowired
    private OkHttpClient okHttpClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {


    }

    private void simpleGet(){
        String url ="http://www.baidu.com";
        Request request = new Request.Builder().url(url).get().build();

        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (!response.isSuccessful()) {
            //失败处理
        }

    }


    private void get() {

        Request.Builder builder = new Request.Builder()
                .url("https://www.baidu.com")
                .get();

        Call call = okHttpClient.newCall(builder.build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //失败处理
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() != null) {
                    String res = response.body().string();
                    // ...
                }

            }

        });
    }
}
